package handler

import (
	"gin-products/api/request"
	"gin-products/consts"
	"gin-products/inter/dao"
	"gin-products/inter/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{

		Mobile: req.Mobile,
		//Password:  req.Password,
		//Email:     req.Email,

	}, &user)
	if user.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "账号已存在",
			"data": nil,
		})
		return
	}
	user = model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
		Email:    req.Email,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "用户注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户注册成功",
		"data": user,
	})

}

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{

		Mobile: req.Mobile,
		//Password:  req.Password,
		//Email:     req.Email,

	}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "账号不存在",
			"data": nil,
		})
		return
	}
	if user.Password != req.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "密码错误",
			"data": user,
		})
	}
	j := jwt2.NewJWT(consts.JWT_SECRET_KEY)
	claims := jwt2.CustomClaims{
		ID: user.Id,

		StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Unix() + 3600},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户登录成功",
		"data": map[string]interface{}{
			"token": token,
			"user":  user,
		},
	})

}

func RefreshToken(c *gin.Context) {
	token, err := jwt2.NewJWT(consts.JWT_SECRET_KEY).RefreshToken(c.Request.Header.Get("x-token"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  "token接收错误",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "token更新成功",
		"data": map[string]interface{}{
			"token": token,
		},
	})
}
